<!-- 医保收费弹窗 -->
<template>
  <a-modal :open="open" :width="800" title="收费" centered :footer="null" @cancel="onCancel">
    <a-form :model="formState" class="cost-form-style pb-4" :label-col="{ style: { width: '100px' } }">
      <div class="flex flex-wrap">
        <template v-if="isPreferential">
          <a-form-item label="本次应收" class="w-1/2">
            <div class="mt-2 text-red-500 font-bold">
              <span>￥</span>
              <span class="pl-1">{{ formatAmount(registerPrice) }}</span>
            </div>
          </a-form-item>
          <a-form-item label="本次优惠" class="w-1/2">
            <a-input v-model:value="discountAmount" v-input-selection placeholder="0.00" size="large" @blur="onBlur()" @input="onDiscountInput">
              <template #prefix> <span class="text-gray-400">￥</span> </template>
            </a-input>
          </a-form-item>
          <a-form-item label="分币误差" class="w-1/2">
            <div class="mt-2">
              <span>￥</span>
              <span class="pl-1">{{ formatAmount(differenceAmount) }}</span>
            </div>
          </a-form-item>
        </template>
        <div class="w-full flex">
          <div class="w-2/5 flex items-center">
            <span class="text-lg">本次实收</span>
            <span class="pl-1 text-2xl font-semibold" :class="+realAmount < 0 ? 'text-primary' : 'text-red-500'">￥{{ formatAmount(realAmount) }}</span>
          </div>
          <div v-if="chargeData" class="w-3/5 flex flex-wrap">
            <div class="w-1/2">
              <span class="text-grey pr-2">住院费用</span>
              <span class="text-base font-semibold">￥{{ formatAmount(chargeData.zyfy) }}</span>
            </div>
            <div class="w-1/2 flex">
              <span class="text-grey pr-2">医保支付</span>
              <span class="text-base font-semibold">￥{{ formatAmount(chargeData.ybzf) }}</span>
              <a-popover trigger="click">
                <template #content>
                  <div class="w-[520px] p-4 flex flex-wrap">
                    <BaseTitle title="医保费用结算明细" class="!w-full" />
                    <a-divider class="!m-1" />
                    <LabelValue label="医疗总费用" class="!w-3/5" :value="'￥' + formatAmount(chargeData.ybsj.setlinfo.medfee_sumamt)" />
                    <LabelValue label="全自费金额" class="!w-2/5" :value="'￥' + formatAmount(chargeData.ybsj.setlinfo.fulamt_ownpay_amt)" />
                    <LabelValue label="实际支付起付线" class="!w-3/5" :value="'￥' + formatAmount(chargeData.ybsj.setlinfo.act_pay_dedc)" />
                    <LabelValue label="统筹基金支出" class="!w-2/5" :value="'￥' + formatAmount(chargeData.ybsj.setlinfo.hifp_pay)" />
                    <LabelValue label="居民大病保险资金支出" class="!w-3/5" :value="'￥' + formatAmount(chargeData.ybsj.setlinfo.hifmi_pay)" />
                    <LabelValue label="医院负担金额" class="!w-2/5" :value="'￥' + formatAmount(chargeData.ybsj.setlinfo.hosp_part_amt)" />
                    <LabelValue label="符合政策范围金额" class="!w-3/5" :value="'￥' + formatAmount(chargeData.ybsj.setlinfo.inscp_scp_amt)" />
                    <LabelValue label="医疗救助基金支出" class="!w-2/5" :value="'￥' + formatAmount(chargeData.ybsj.setlinfo.maf_pay)" />
                    <LabelValue label="个人负担总金额" class="!w-3/5" :value="'￥' + formatAmount(chargeData.ybsj.setlinfo.psn_part_amt)" />
                    <LabelValue label="个人账户支出" class="!w-2/5" :value="'￥' + formatAmount(chargeData.ybsj.setlinfo.acct_pay)" />
                    <LabelValue label="个人现金支出" class="!w-3/5" :value="'￥' + formatAmount(chargeData.ybsj.setlinfo.psn_cash_pay)" />
                    <LabelValue label="超限价自费费用" class="!w-2/5" :value="'￥' + formatAmount(chargeData.ybsj.setlinfo.overlmt_selfpay)" />
                    <LabelValue label="公务员医疗补助资金支出" class="!w-3/5" :value="'￥' + formatAmount(chargeData.ybsj.setlinfo.cvlserv_pay)" />
                    <LabelValue label="统筹基金支付比例" class="!w-2/5" :value="'￥' + formatAmount(chargeData.ybsj.setlinfo.pool_prop_selfpay)" />
                    <LabelValue label="企业补充医疗保险基金支出" class="!w-3/5" :value="'￥' + formatAmount(chargeData.ybsj.setlinfo.hifes_pay)" />
                    <LabelValue label="基金支付总额" class="!w-2/5" :value="'￥' + formatAmount(chargeData.ybsj.setlinfo.fund_pay_sumamt)" />
                    <LabelValue label="职工大额医疗费用补助基金支出" class="!w-3/5" :value="'￥' + formatAmount(chargeData.ybsj.setlinfo.hifob_pay)" />
                    <LabelValue label="先行自付金额" class="!w-2/5" :value="'￥' + formatAmount(chargeData.ybsj.setlinfo.preselfpay_amt)" />
                    <LabelValue label="个人账户共济支付金额" class="!w-3/5" :value="'￥' + formatAmount(chargeData.ybsj.setlinfo.acct_mulaid_pay)" />
                    <LabelValue label="其他支出" class="!w-2/5" :value="'￥' + formatAmount(chargeData.ybsj.setlinfo.oth_pay)" />
                  </div>
                </template>
                <a-button size="small" class="ml-2" :icon="h(SearchOutlined)" />
              </a-popover>
            </div>
            <div class="w-1/2">
              <span class="text-grey pr-2">押金</span>
              <span class="text-base font-semibold">￥{{ formatAmount(chargeData.yjje) }}</span>
            </div>
            <div class="w-1/2">
              <span class="text-grey pr-2">个人支付</span>
              <span class="text-base font-semibold">￥{{ formatAmount(chargeData.grzf) }}</span>
              <span class="text-grey pr-2"> (分币{{ formatAmount(chargeData.fbwc) }})</span>
            </div>
          </div>
        </div>
      </div>
      <a-divider />
      <div class="flex flex-wrap mt-6">
        <a-form-item v-for="item in chargeTypeList" :key="item.id" :label="item.zffsmc" class="w-1/2">
          <a-input-group class="!flex">
            <a-input
              :key="item.zffsdm"
              v-model:value="formState[item.zffsdm]"
              v-input-selection
              size="large"
              placeholder="0.00"
              @blur="onBlur(item.zffsdm)"
              @change="handlerChangePrice(item.zffsdm)"
            >
              <template #prefix> <span class="text-gray-400">￥</span> </template>
            </a-input>
            <a-button class="!w-10 !rounded-l-none border-l-0" size="large" @click="onclickAllPrice(item)">
              <template #icon>
                <ArrowLeftOutlined class="text-gray-400 text-xs" />
              </template>
            </a-button>
          </a-input-group>
        </a-form-item>
      </div>
      <a-divider />
      <div class="flex mt-8 items-center">
        <a-form-item v-if="isShowAmount" label="找零" class="w-1/2 !mb-0">
          <div class="mt-2 text-red-500 font-bold">
            <span>￥</span>
            <span class="pl-1">{{ formatAmount(changeAmount) }}</span>
          </div>
        </a-form-item>
        <!-- 占位 -->
        <div v-else class="w-1/2 !mb-0"></div>
        <a-form-item class="w-1/2 text-right !pr-8 !mb-0">
          <a-button type="default" class="mr-4" @click="onCancel">取消</a-button>
          <a-button type="primary" :disabled="disabledState" @click="onOk">确定</a-button>
        </a-form-item>
      </div>
    </a-form>
  </a-modal>
</template>
<script setup>
import { onMounted, ref, watch, h } from 'vue'
import { ArrowLeftOutlined, SearchOutlined } from '@ant-design/icons-vue'
import { message } from 'ant-design-vue'
import { post } from '@/utils/request'
import { formatAmount } from '@/utils/format.js'

const emit = defineEmits(['update:open', 'success'])
const props = defineProps({
  open: Boolean,
  registerPrice: {
    type: Number,
    default: () => 0
  },
  difference: {
    type: Number,
    default: () => 0
  },
  isPreferential: {
    type: Boolean,
    default: true
  },
  chargeData: {
    type: Object,
    default: () => ({})
  },
  isShowAmount: {
    type: Boolean,
    default: true
  }
})
const chargeTypeList = ref([])
const discountAmount = ref('0.00') // 优惠金额
const differenceAmount = ref(0) // 分币误差
const changeAmount = ref(0) // 找零
const formState = ref({})
const realAmount = ref(0)
const ePayTotal = ref(0) // 电子支付的总和
const priceAll = ref(0) // 全部的总和
const disabledState = ref(true)

// 实收金额 = 应收金额-优惠金额-分币误差
// const realAmount = computed(() => {
//   return props.registerPrice - Number(discountAmount.value) - Number(differenceAmount.value)
// })
// 找零=现金+电子支付-实收金额
const countSmallChange = () => {
  const zero = +formState.value['xjzf'] + ePayTotal.value - Number(realAmount.value)
  changeAmount.value = formatAmount(zero)
}
const handlerChangePrice = (zffsdm = '') => {
  ePayTotal.value = 0
  priceAll.value = 0
  // 限制输入内容的范围
  formState.value[zffsdm] = formState.value[zffsdm].replace(/[^\d.]/g, '')
  // 计算电子支付的总和
  for (const key in formState.value) {
    if (key !== 'xjzf') {
      ePayTotal.value += Number(formState.value[key])
    }
  }
  // 判断电子支付的总和是否大于实收金额
  if (ePayTotal.value > realAmount.value) {
    formState.value[zffsdm] = null
    formState.value['xjzf'] = '0.00'
    changeAmount.value = 0
    return message.error('电子支付累计金额不可大于实收金额')
  }
  // 判断当前输入的是否是现金金额
  if (zffsdm === 'xjzf') {
    // 如果现金+电子支付>实收金额，计算找零
    if (+formState.value['xjzf'] + ePayTotal.value > +realAmount.value) {
      countSmallChange()
    } else {
      changeAmount.value = 0
    }
  } else {
    // 判断电子支付金额是否等于0，如果不等于，判断实收金额是否大于电子支付金额或者是否相等
    if (ePayTotal.value !== 0) {
      if (realAmount.value > ePayTotal.value || realAmount.value === ePayTotal.value) {
        // 现金=实收金额-电子支付
        const cash = realAmount.value - ePayTotal.value < 0 ? 0 : formatAmount(realAmount.value - ePayTotal.value)
        formState.value['xjzf'] = +cash ? formatAmount(cash) : '0.00'
        countSmallChange()
      }
    } else {
      formState.value['xjzf'] = '0.00'
    }
  }

  for (const key in formState.value) {
    priceAll.value += Number(formState.value[key])
  }
  if (
    Number(formatAmount(priceAll.value)) > Number(formatAmount(realAmount.value)) ||
    Number(formatAmount(priceAll.value)) === Number(formatAmount(realAmount.value))
  ) {
    disabledState.value = false
  } else {
    disabledState.value = true
  }
}

// 判断优惠金额和支付，鼠标离开保留两位
const onBlur = (zffsdm = '') => {
  if (zffsdm !== '') {
    formState.value[zffsdm] = formState.value[zffsdm] ? formatAmount(formState.value[zffsdm]) : ''
  } else {
    discountAmount.value = discountAmount.value ? formatAmount(discountAmount.value) : ''
  }
}
// 单项全部收费
const onclickAllPrice = (item) => {
  formState.value = {}
  formState.value = { [item.zffsdm]: formatAmount(realAmount.value) }
  changeAmount.value = 0
  disabledState.value = false
}
const onRest = () => {
  discountAmount.value = '0.00'
  formState.value = {}
  changeAmount.value = 0
}

const getChargeTypeList = async () => {
  const { code, data } = await post('/outp/oupCharge/getChargeTypeList')
  if (code !== 0) return
  chargeTypeList.value = data
}

const onOk = async () => {
  const chargeData = { ...formState.value }
  chargeTypeList.value.forEach((item) => {
    chargeData[item.zffsdm] = chargeData[item.zffsdm] ? chargeData[item.zffsdm] : 0
  })
  const params = {
    ...chargeData,
    change: changeAmount.value,
    fbyh: chargeData.fbwc,
    yhje: discountAmount.value,
    ysje: formatAmount(props.registerPrice),
    ssje: formatAmount(realAmount.value)
  }
  emit('success', params)
  onCancel()
}

const onDiscountInput = () => {
  formState.value = {}
  changeAmount.value = 0
  discountAmount.value = discountAmount.value.replace(/[^\d.]/g, '')
  if (+discountAmount.value > +props.registerPrice) {
    message.error('优惠金额不能大于应收金额')
    discountAmount.value = '0.00'
  }
  getDiscountAmount()
}
const getDiscountAmount = async () => {
  // const { code, data } = await post('/outp/oupCharge/getPennyDiscount', {
  //   ysje: Number(props.registerPrice), //应收金额
  //   yhje: Number(discountAmount.value) //优惠金额
  // })
  // if (code !== 0) return
  // differenceAmount.value = props.difference !== 0 ? props.difference : data.fbwc
  // realAmount.value = data.ssje
  realAmount.value = Number(props.chargeData.ssje)
}

watch(
  () => props.open,
  (val) => {
    if (val) {
      getDiscountAmount()
      disabledState.value = true
    }
    onRest()
  },
  { immediate: true }
)

const onCancel = () => {
  emit('update:open', false)
}
onMounted(() => {
  getChargeTypeList()
})
</script>
<style lang="less" scoped>
.cost-form-style {
  :deep(.ant-form-item) {
    padding: 0 3px;

    .ant-form-item-label {
      width: 75px;
      padding-top: 4px;

      label {
        color: #5d5d5d;
        font-size: 16px;
      }
    }

    .ant-form-item-control {
      flex: none;
      width: 240px;
      color: #2b2b2b;
      font-size: 15px;

      .ant-input {
        text-align: right;
      }
    }
  }

  .ant-divider {
    margin: 12px 0;
  }
}

.in-title {
  color: #a4adb3;
}
</style>
